package cn.akira.domain.strategy.service.armory;

import cn.akira.domain.strategy.model.entity.StrategyAwardEntity;
import cn.akira.domain.strategy.model.entity.StrategyEntity;
import cn.akira.domain.strategy.model.entity.StrategyRuleEntity;
import cn.akira.domain.strategy.repository.IStrategyRepository;
import cn.akira.types.common.Constants;
import cn.akira.types.enums.ResponseCode;
import cn.akira.types.exception.AppException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.security.SecureRandom;
import java.util.*;

/**
 * @author fjl95
 * @date 2025/5/11
 * @description 策略装配库，负责初始化策略计算
 */
@Slf4j
@Service
public class StrategyArmoryDispatch implements IStrategyArmory , IStrategyDispatch {

    @Resource
    private IStrategyRepository strategyRepository;

    /*
    生成策略对应的随机数-奖品对应表
     */
    @Override
    public boolean assembleLotteryStrategy(Long strategyId) {

        //1.查询当前策略对应的奖品
        List<StrategyAwardEntity> strategyAwardEntities = strategyRepository.queryStrategyAwardList(strategyId);
        //1.1无权重规则下的随机数奖品表设置
        assembleLotteryStrategy(String.valueOf(strategyId), strategyAwardEntities);
        //3.1 默认装配库存信息
        //缓存奖品库存
        for(StrategyAwardEntity strategyAwardEntity : strategyAwardEntities) {
            Integer awardId = strategyAwardEntity.getAwardId();
            Integer awardCountSurplus = strategyAwardEntity.getAwardCountSurplus();
            cacheStrategyAwardCount(strategyId,awardId,awardCountSurplus);
        }
        //2.权重策略配置 - 适用于有rule_Weight情况下的权重规则配置
        //2.2查找当前策略信息
        StrategyEntity strategyEntity = strategyRepository.queryStrategyEntityByStrategyId(strategyId);
        //2.3查看当前策略是否有rule_weight关键字
        String ruleWeight = strategyEntity.getRuleWeight();
        if (null == ruleWeight) return true;
        //2.4根据策略ID，rule_weight找出对应的规则细节
        StrategyRuleEntity strategyRuleEntity = strategyRepository.queryStrategyRule(strategyId,ruleWeight);
        if (null == strategyRuleEntity) {
            //抛出异常
            throw new AppException(ResponseCode.STRATEGY_RULE_WEIGHT_IS_NULL.getCode(),ResponseCode.STRATEGY_RULE_WEIGHT_IS_NULL.getInfo());
        }
        //2.5根据规则，拿到value:也就是权重具体划分细节
        Map<String,List<Integer>> ruleWeightValueMap = strategyRuleEntity.getRuleWeightValues();
        //2.6根据细节，筛选不同的奖品，构造不同的随机数奖品表
        Set<String> keys = ruleWeightValueMap.keySet();
        for (String key : keys) {
            List<Integer> ruleWeightValues = ruleWeightValueMap.get(key);
            ArrayList<StrategyAwardEntity> strategyAwardEntitiesClone = new ArrayList<>(strategyAwardEntities);
            strategyAwardEntitiesClone.removeIf(entity -> !ruleWeightValues.contains(entity.getAwardId()));
            assembleLotteryStrategy(String.valueOf(strategyId).concat("_").concat(key), strategyAwardEntitiesClone);
        }
        return true;
    }

    @Override
    public boolean assembleLotteryStrategyByActivityId(Long activityId) {
        //根据活动查询到策略
        Long strategyId = strategyRepository.queryStrategyIdByActivityId(activityId);
        return assembleLotteryStrategy(strategyId);

    }

    //缓存奖品库存
    private void cacheStrategyAwardCount(Long strategyId, Integer awardId, Integer awardCountSurplus) {
        String cacheKey = Constants.RedisKey.STRATEGY_AWARD_COUNT_KEY + strategyId + Constants.UNDERLINE + awardId;
        strategyRepository.cacheStrategyAwardCount(cacheKey,awardCountSurplus);
    }

    /**
     * 封装起来的装配奖品表逻辑
     * @param key
     * @param strategyAwardEntities
     */
    private void assembleLotteryStrategy(String key, List<StrategyAwardEntity> strategyAwardEntities) {
        // 1. 获取最小概率值
        BigDecimal minAwardRate = strategyAwardEntities.stream()
                .map(StrategyAwardEntity::getAwardRate)
                .min(BigDecimal::compareTo)
                .orElse(BigDecimal.ZERO);

        // 2. 获取概率值总和
        BigDecimal totalAwardRate = strategyAwardEntities.stream()
                .map(StrategyAwardEntity::getAwardRate)
                .reduce(BigDecimal.ZERO, BigDecimal::add);

        // 3. 用 1 % 0.0001 获得概率范围，百分位、千分位、万分位
        BigDecimal rateRange = totalAwardRate.divide(minAwardRate, 0, RoundingMode.CEILING);

        // 4. 生成策略奖品概率查找表「这里指需要在list集合中，存放上对应的奖品占位即可，占位越多等于概率越高」
        List<Integer> strategyAwardSearchRateTables = new ArrayList<>(rateRange.intValue());
        for (StrategyAwardEntity strategyAward : strategyAwardEntities) {
            Integer awardId = strategyAward.getAwardId();
            BigDecimal awardRate = strategyAward.getAwardRate();
            // 计算出每个概率值需要存放到查找表的数量，循环填充
            for (int i = 0; i < rateRange.multiply(awardRate).setScale(0, RoundingMode.CEILING).intValue(); i++) {
                strategyAwardSearchRateTables.add(awardId);
            }
        }

        // 5. 对存储的奖品进行乱序操作
        Collections.shuffle(strategyAwardSearchRateTables);

        // 6. 生成出Map集合，key值，对应的就是后续的概率值。通过概率来获得对应的奖品ID
        Map<Integer, Integer> shuffleStrategyAwardSearchRateTable = new LinkedHashMap<>();
        for (int i = 0; i < strategyAwardSearchRateTables.size(); i++) {
            shuffleStrategyAwardSearchRateTable.put(i, strategyAwardSearchRateTables.get(i));
        }

        // 7. 存放到 Redis
        strategyRepository.storeStrategyAwardSearchRateTable(key, rateRange, shuffleStrategyAwardSearchRateTable);
    }


    @Override
    public Integer getRandomAwardId(Long strategyId) {
        String key = String.valueOf(strategyId);

        //获得策略下的随机数范围
        int rateRange = strategyRepository.getRateRange(key);

        //通过生成的随机值，查找奖品
        return strategyRepository.getStrategyAwardAssemble(key,new SecureRandom().nextInt(rateRange));
    }

    @Override
    public Integer getRandomAwardId(Long strategyId, String ruleWeightValue) {
        String key = String.valueOf(strategyId).concat("_").concat(ruleWeightValue);
        //获得策略下的随机数范围
        int rateRange = strategyRepository.getRateRange(key);

        //通过生成的随机值，查找奖品
        return strategyRepository.getStrategyAwardAssemble(key,new SecureRandom().nextInt(rateRange));
    }

    //对redis的减库存操作
    @Override
    public Boolean subtractionAwardStock(Long strategyId, Integer awardId,Date endDateTime) {
        String cacheKey = Constants.RedisKey.STRATEGY_AWARD_COUNT_KEY + strategyId + Constants.UNDERLINE + awardId;
        return strategyRepository.subtractionAwardStock(cacheKey,endDateTime);
    }


}
